import React from "react";
import Draggable from 'react-draggable'
import { drapPositions, drapEnd } from "../service/store";
import Chart from "../charts/Chart";

export default class ChartDrap extends React.Component {
  public ref: any

  public catch: any = {}

  public state = {
    activeDrags: 0,
    deltaPosition: {
      x: 0, y: 0
    },
    controlledPosition: {
      x: -250, y: -500
    }
  }

  public onStart = (...args: any[]) => {
    this.setState({ activeDrags: ++this.state.activeDrags });
  }

  public onStop = (...args: any[]) => {
    drapEnd.next("Chart")
    this.setState({})
    this.setState({ activeDrags: --this.state.activeDrags });
  }


  public onControlledDrag = (e: any, position: any) => {
    const { x, y } = position;
    const positions: Array<[number, number]> = [
      [this.catch.offsetLeft + x, this.catch.offsetTop + y],
      [this.catch.offsetLeft + x + this.catch.clientWidth, this.catch.offsetTop + y],
      [this.catch.offsetLeft + x, this.catch.offsetTop + y + this.catch.clientHeight],
      [this.catch.offsetLeft + x + this.catch.clientWidth, this.catch.offsetTop + y + this.catch.clientHeight],
    ]
    drapPositions.next(positions)
  }

  public handleDrag = (e: any, ui: any) => {
    const { x, y } = this.state.deltaPosition;
    this.setState({
      deltaPosition: {
        x: x + ui.deltaX,
        y: y + ui.deltaY,
      }
    });
  }

  public componentDidMount() {
    this.catch.offsetLeft = this.ref.offsetLeft
    this.catch.offsetTop = this.ref.offsetTop
    this.catch.clientHeight = this.ref.clientHeight
    this.catch.clientWidth = this.ref.clientWidth
  }

  public render() {
    const dragHandlers = { onStart: this.onStart, onStop: this.onStop };
    const { controlledPosition } = this.state;
    return (
      <Draggable position={controlledPosition} onDrag={this.onControlledDrag} {...dragHandlers}>
        <div ref={(ref) => this.ref = ref} className="box" style={{ width: 250, height: 250, background: 'red' }}>
          <div><Chart name={"Chart"} /></div>
          {/* <div>x: {controlledPosition.x.toFixed(0)}, y: {controlledPosition.y.toFixed(0)}</div> */}
        </div>
      </Draggable>
    )
  }
}